var express = require('express')
var router = express.Router()
var fs = require('fs')
var multiparty = require('multiparty');
var bodyParser = require('body-parser');
var FTPS = require('ftps');

/* single page router. */
router.get('/index', function(req, res, next) {
  res.write('api')
  res.end()
})

router.post('/uploadimage', function(req, res, next) {
    var form = new multiparty.Form();
    form.parse(req, function(err, fields, files) {
        var fileName = files.img[0].originalFilename,
            source = fs.createReadStream(files.img[0].path),
            dest = fs.createWriteStream('./config/' + fileName);

        source.pipe(dest);

        source.on('error', function(err) {
            console.log(err);
            res.end();
        });

        source.on('end', function() {
            res.end();
        });
    });

})

router.get('/getconfig', function(req, res, next) {
    var dataString = '';
    fs.readFile('./config/config.json', function(err, data){ 
        if (err) {
            return console.error(err);
        }
        //文件内容
        // console.log(data.toString());
        dataString = JSON.stringify(data.toString());
        res.write(dataString);
        res.end();
    })
});

router.post('/saveconfig', function(req, res, next) {
    var urlencodedParser = bodyParser.urlencoded({ extended : false});
    urlencodedParser(req, res, function(){
        var postData = req.body,
            dataObj = JSON.parse(postData.dataObj);

        fs.writeFile('./config/config.json', JSON.stringify(dataObj),  function(err) {
            if (err) {
                return console.error(err);
            }else{
                res.write(JSON.stringify({}));
                res.end();
            }
        });

    });
});

router.post('/exportconfig', function(req, res, next) {
    var urlencodedParser = bodyParser.urlencoded({ extended : false});
    urlencodedParser(req, res, function(){
        var postData = req.body,
            dataObj = JSON.parse(postData.dataObj);
            flag1 = false,
            flag2 = false,
            flag3 = false,
            flag4 = false,
            format = function(val){
                return val > 9 ? val : '0' + val;
            };

        // console.log(dataObj);

        var dirList = fs.readdirSync('../xunlei.com/ssr.xzb.xunlei.com/config');
        dirList.forEach(function(fileName){
            console.log(fileName);
            fs.unlinkSync('../xunlei.com/ssr.xzb.xunlei.com/config/' + fileName);
            // if(fileName.indexOf('.js') == -1){
            //     fs.unlinkSync('../xzb.xunlei.com/config/' + fileName);
            // }
            
        });

        fs.writeFile('../xunlei.com/ssr.xzb.xunlei.com/config/config.json', JSON.stringify(dataObj),  function(err) {
            if (err) {
                return console.error(err);
            }else{
                flag1 = true;
                if(flag1 && flag2 && flag3 && flag4){
                    res.write(JSON.stringify({}));
                    res.end();
                }
            }
        });

        fs.readFile('./config/' + dataObj.pcImg, function(err, data){ 
            if (err) {
                return console.error(err);
            }

            fs.writeFile('../xunlei.com/ssr.xzb.xunlei.com/config/' + dataObj.pcImg, data,  function(err) {
                if (err) {
                    return console.error(err);
                }else{
                    flag2 = true;
                    if(flag1 && flag2 && flag3 && flag4){
                        res.write(JSON.stringify({}));
                        res.end();
                    }
                }
            });
        });

        fs.readFile('./config/' + dataObj.mobileImg, function(err, data){ 
            if (err) {
                return console.error(err);
            }

            fs.writeFile('../xunlei.com/ssr.xzb.xunlei.com/config/' + dataObj.mobileImg, data,  function(err) {
                if (err) {
                    return console.error(err);
                }else{
                    flag3 = true;
                    if(flag1 && flag2 && flag3 && flag4){
                        res.write(JSON.stringify({}));
                        res.end();
                    }
                }
            });
        });

        fs.readFile('./config/log.json', function(err, data){ 
            if (err) {
                return console.error(err);
            }

            var logData =  JSON.parse(data);
            var now = new Date(),
                newLog = {},
                str = now.getFullYear() + '-' + format(now.getMonth() + 1) + '-' + format(now.getDate()) + ' ' + format(now.getHours()) + ':' + format(now.getMinutes()) + ':' + format(now.getSeconds());
                
            newLog[str] = dataObj;
            logData.push(newLog);

            fs.writeFile('./config/log.json', JSON.stringify(logData),  function(err) {
                if (err) {
                    return console.error(err);
                }else{
                    flag4 = true;
                    if(flag1 && flag2 && flag3 && flag4){
                        res.write(JSON.stringify({}));
                        res.end();
                    }
                }
            });
        });
       

    });
});

router.post('/sendtotest', function(req, res, next) {
    var ftps = new FTPS({
        host: '10.10.98.3',
        username: 'root1',
        password: '27732928',
        protocol: 'sftp',
        port: 22,
        escape: true,
        retries: 2,
        timeout: 1000,
        requiresPassword: true,
        autoConfirm: true,
        cwd: ''
    });

    // ftps.put('../xzb.xunlei.com/config/*', '/data/vhosts/xzb.xunlei.com/config').exec(function(err, response){
    //     if(err){
    //        return console.error(err); 
    //     }else{
    //         res.write(JSON.stringify({}));
    //         res.end();
    //     }
    // });

    ftps.mirror({
        remoteDir: '/data/vhosts/xunlei.com/ssr.xzb.xunlei.com/config',
        localDir: '../xunlei.com/ssr.xzb.xunlei.com/config',
        parallel: true,
        upload: true,
        options: '-e'
    }).exec(function(err, response){
        if(err){
           return console.error(err); 
        }else{
            res.write(JSON.stringify({}));
            res.end();
        }
    });

});

module.exports = router;
